package com.lc.luzhengtang.activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.method.TransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.MainActivity;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean2;
import com.lc.luzhengtang.bean.NewLoginBean;
import com.lc.luzhengtang.conn.ConnLogin;
import com.lc.luzhengtang.conn.ConnWx;
import com.lc.luzhengtang.util.LovelyToast;
import com.lc.luzhengtang.util.Validator;
import com.lc.luzhengtang.view.ClearEditText;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilMatches;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.lc.luzhengtang.R.id.text_forget_password;

/**
 * Created by Administrator on 2017/5/3.
 */

public class LoginActivity extends BaseActivity implements Handler.Callback {
    @BindView(R.id.img_news)
    ImageView imgNews;
    @BindView(R.id.edit_phone)
    ClearEditText editPhone;
    @BindView(R.id.edit_newpwd)
    ClearEditText editNewpwd;
    @BindView(R.id.edit_code)
    EditText editCode;
    @BindView(R.id.text_sendbtn)
    TextView textSendbtn;

    @BindView(R.id.text_register)
    TextView textRegister;
    @BindView(R.id.btn_login)
    Button btnLogin;

    @BindView(R.id.layout_getCode)
    LinearLayout layoutGetCode;
    @BindView(R.id.img_wx_login)
    ImageView imgWxLogin;
    String openid;
    String pic_url;
    String name;
    public static final String TURNTOINDEX = "turn_to_index";
    UMAuthListener authListener = new UMAuthListener() {
        /**
         * @desc 授权开始的回调
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
//            SocializeUtils.safeShowDialog(dialog);
        }

        /**
         * @desc 授权成功的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param data 用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
//            SocializeUtils.safeCloseDialog(dialog);
            String temp = "";
            for (String key : data.keySet()) {
                temp = temp + key + " : " + data.get(key) + "\n";
                Log.d(data.get(key), "ggggggggggggggggggggggg");
            }

            openid = data.get("openid");
            pic_url = data.get("iconurl");
            name = data.get("name");
            getLogin2();

          /* */

        }

        /**
         * @desc 授权失败的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "失败：" + t.getMessage(), Toast.LENGTH_LONG).show();
        }

        /**
         * @desc 授权取消的回调
         * @param platform 平台名称
         * @param action 行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
//            SocializeUtils.safeCloseDialog(dialog);
            Toast.makeText(LoginActivity.this, "取消了", Toast.LENGTH_LONG).show();
        }
    };
    @BindView(R.id.img_phone)
    ImageView imgPhone;
    @BindView(R.id.img_pwd)
    ImageView imgPwd;
    @BindView(R.id.img_close)
    ImageView imgClose;
    @BindView(R.id.img_open)
    ImageView imgOpen;
    @BindView(R.id.text_forget_password)
    TextView textForgetPassword;
    @BindView(R.id.text_other_login)
    TextView textOtherLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
//            window.setStatusBarColor(getResources().getColor(R.color.umeng_blue));
        }
    }

    @OnClick({R.id.img_news, R.id.edit_phone, R.id.edit_newpwd, R.id.edit_code, R.id.text_sendbtn, text_forget_password, R.id.text_register, R.id.btn_login, R.id.img_wx_login,R.id.img_close,R.id.img_open})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_news:
                finish();
                break;
            case R.id.edit_phone:
                break;
            case R.id.edit_newpwd:
                break;
            case R.id.edit_code:
                break;
            case R.id.text_sendbtn:
                break;
            case text_forget_password:
                //注释的是申诉
//                startActivity(new Intent(LoginActivity.this, AppealActivity.class));
                startActivity(new Intent(LoginActivity.this, ForgetPasswordActivity2.class));
                finish();
                break;
            case R.id.text_register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;

            case R.id.btn_login:

                if (TextUtils.isEmpty(editPhone.getText().toString().trim())) {
                    LovelyToast.makeText(LoginActivity.this, "手机号不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!Validator.isMobile(editPhone.getText().toString())) {
                    LovelyToast.makeText(LoginActivity.this, "请输入正确的手机号码", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!UtilMatches.checkMobile(editPhone.getText().toString())) {
                    LovelyToast.makeText(LoginActivity.this, "请输入正确的手机号", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                    // UtilToast.show(RegisterActivity.this, "请输入正确的手机号");
                } else if (TextUtils.isEmpty(editNewpwd.getText().toString())) {
                    LovelyToast.makeText(LoginActivity.this, "密码不能为空", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else if (!Validator.isPassword(editNewpwd.getText().toString())) {
                    LovelyToast.makeText(LoginActivity.this, "请输入6~12位数字或英文密码", 0, LovelyToast
                            .SUCCESS, LovelyToast.SCALE);
                } else {
                    getLogin();
                }
                break;

            case R.id.img_wx_login:
                UMShareConfig config = new UMShareConfig();
                config.isNeedAuthOnGetUserInfo(true);
                UMShareAPI.get(LoginActivity.this).setShareConfig(config);
//               UMShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
//               UMShareAPI.get(LoginActivity.this).doOauthVerify(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, authListener);
                //执行授权,获取用户信息
                //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
               /* UMShareAPI.get(this).getPlatformInfo(this, share_media, authListener);
                @Override
                protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                super.onActivityResult(requestCode, resultCode, data);
                UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);
            }*/
                break;

//            R.id.img_close,R.id.img_open
            case R.id.img_close:
                //密文
              /*  HideReturnsTransformationMethod method1 = HideReturnsTransformationMethod.getInstance();
                editNewpwd.setTransformationMethod(method1);*/

                TransformationMethod method = HideReturnsTransformationMethod.getInstance();
                editNewpwd.setTransformationMethod(method);
                imgClose.setVisibility(View.GONE);

                imgOpen.setVisibility(View.VISIBLE);
                break;
            case R.id.img_open:
//                MainActivity.this.passwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());

                editNewpwd.setTransformationMethod(PasswordTransformationMethod.getInstance());

                imgClose.setVisibility(View.VISIBLE);

                imgOpen.setVisibility(View.GONE);

                break;

        }
    }


    public void getLogin() {
        new ConnLogin(editPhone.getText().toString().trim(), editNewpwd.getText().toString(), new AsyCallBack<NewLoginBean>() {

            @Override
            public void onSuccess(String toast, int type, Object o, NewLoginBean loginBean) throws Exception {
                LovelyToast.makeText(LoginActivity.this, loginBean.getMessage(), 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
                BaseApplication.basePreferences.saveUid(loginBean.getData().getId() + "");
//                BaseApplication.basePreferences.saveUserName(loginBean.getData().getId() + "");
                BaseApplication.basePreferences.saveUserName(loginBean.getData().getUsername());
                BaseApplication.basePreferences.saveName(loginBean.getData().getName());
                BaseApplication.basePreferences.saveMobile(loginBean.getData().getMobile());
                BaseApplication.basePreferences.savePhone(loginBean.getData().getPhone());
                BaseApplication.basePreferences.saveAvatar(loginBean.getData().getAvatar());
                BaseApplication.basePreferences.savePassword(loginBean.getData().getPassword());
                BaseApplication.basePreferences.savePassword(loginBean.getData().getPayword());
                BaseApplication.basePreferences.saveRole_id(loginBean.getData().getRole_id() + "");
                BaseApplication.basePreferences.saveSex(loginBean.getData().getSex());
                BaseApplication.basePreferences.saveEmail(loginBean.getData().getEmail());
                BaseApplication.basePreferences.saveQq(loginBean.getData().getQq());
                BaseApplication.basePreferences.saveCreate_time(loginBean.getData().getCreate_time());
                BaseApplication.basePreferences.saveDatetimes(loginBean.getData().getDatetimes());
//                BaseApplication.basePreferences.saveUserNames(loginBean.getData().getUsername());
                BaseApplication.basePreferences.saveFlag("1");
                BaseApplication.basePreferences.saveSign("1");
//                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(new Intent(TURNTOINDEX));

                LoginActivity.this.finish();

//                finish();
            }


            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            /*    LovelyToast.makeText(LoginActivity.this, ConnLogin.TOAST, 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
             /*   LovelyToast.makeText(LoginActivity.this, ConnLogin.TOAST, 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);*/
                //    finish();
            }
        }


        ).execute(LoginActivity.this, false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调


    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

  /*  Intent intent = new Intent();
    intent.putExtra("openid", openid);
    intent.putExtra("pic_url", pic_url);
    intent.putExtra("name", name);*/


    public void getLogin2() {
        new ConnWx(openid, new AsyCallBack<CommenBean2>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, CommenBean2 commenBean2) throws Exception {
                super.onSuccess(toast, type, o, commenBean2);

                if (commenBean2.getCode() == 200) {
                    BaseApplication.basePreferences.saveUid(commenBean2.getMember_id());
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                } else {
                    Intent intent = new Intent();
                    intent.putExtra("openid", openid);
                    intent.putExtra("pic_url", pic_url);
                    intent.putExtra("name", name);
                    intent.setClass(LoginActivity.this, BindMobilActivity.class);
                    startActivity(intent);
                }


                /*  if (commenBean2.getMessage().equals("用户已存在")) {
                    BaseApplication.basePreferences.saveUid(commenBean2.getMember_id());
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));



                } else {
                    Intent intent = new Intent();
                    intent.putExtra("openid", openid);
                    intent.putExtra("pic_url", pic_url);
                    intent.putExtra("name", name);
                    intent.setClass(LoginActivity.this, BindMobilActivity.class);
                    startActivity(intent);
//                    BaseApplication.basePreferences.saveUid(openid);
                }*/
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
            }

            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
            }
        }


        ).execute(LoginActivity.this, false);
    }



}
